package com.aube.base.goods;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.aube.interact.base.R;
import com.huyn.baseframework.ImageLoader;
import com.huyn.baseframework.dynamicload.video.model.GoodsModel;
import com.huyn.baseframework.utils.StringUtils;
import com.huyn.baseframework.utils.Utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by hill on 16/12/26.
 */

public class GoodsCarouselView extends FrameLayout {
    private final String TAG = "Aube/GoodsCarouselView";

    private Context mContext;

    private LinearLayout mDotsLayout;
    private List<ImageView> mPagesIV = new ArrayList<>();
    private List<ImageView> mDotsIV = new ArrayList<>();
    private CustomDurationViewPager mViewPager;
    private int currentItem = 0;

    private CustomPagerAdapter mCustomPagerAdapter;
    private CustomViewPagerScroller mScroller;

    private Handler mHandler = new Handler();
    private Timer mTimer = null;
    public int currentIndex=0;

    public GoodsCarouselView(Context context) {
        this(context, null);
    }

    public GoodsCarouselView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public GoodsCarouselView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        initView();
    }

    private void initView() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.aube_intera_layout_goodscarousel, this, true);
        mViewPager = (CustomDurationViewPager) view.findViewById(R.id.goodscarousel_pager);
        mDotsLayout = (LinearLayout) view.findViewById(R.id.goodscarousel_dots);

        mViewPager.setScrollDurationFactor(3);
        mViewPager.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction()==MotionEvent.ACTION_DOWN){
                    stopAutoScroller();
                }else if(event.getAction()==MotionEvent.ACTION_UP){
                    startAutoScroller();
                }
                return false;
            }
        });
    }

    public void fillData(final GoodsModel goods) {
        if(StringUtils.isBlank(goods.getGoodsShowPicUrl()))
            return;

        if(goods.goodsVo == null || goods.goodsVo.picRespVoList == null)
            return;

        mCustomPagerAdapter = new CustomPagerAdapter();
        mViewPager.setAdapter(mCustomPagerAdapter);
        mViewPager.setFocusable(true);
        mViewPager.setCurrentItem(currentItem, true);
        mViewPager.addOnPageChangeListener(new CustomOnPageChangeListener());

        for(int i = 0; i < goods.goodsVo.picRespVoList.size(); i++) {
            ImageView imageView = new ImageView(mContext);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            ImageLoader.getInstance(getContext()).fillImage(imageView, goods.goodsVo.picRespVoList.get(i).picurl, 450, 600);
            Utils.Log(TAG, "[fillData] picurl = " + goods.goodsVo.picRespVoList.get(i).picurl);

            mPagesIV.add(imageView);

            ImageView dotIV = new ImageView(mContext);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            params.leftMargin = params.rightMargin = 4;
            mDotsLayout.addView(dotIV, params);
            mDotsIV.add(dotIV);
        }

        mCustomPagerAdapter.notifyDataSetChanged();

        initHandle();
    }

    public void dismiss() {
        if(mPagesIV != null)
            mPagesIV.clear();

        if(mDotsLayout != null)
            mDotsLayout.removeAllViews();

        if(mDotsIV != null)
            mDotsIV.clear();

        stopAutoScroller();

        ((ViewGroup)getParent()).removeView(this);

        Utils.Log(TAG, "[dismiss] mPagesIV.size = " + mPagesIV.size() + ", mDotsIV.size = " + mDotsIV.size());
    }

    public void initHandle(){
        mHandler = new Handler() {
            @SuppressLint("NewApi")
            public void handleMessage(Message msg) {
                if(msg.what == 1) {
                    //setScrollerTime(700);
                    mViewPager.setCurrentItem(currentIndex, true);
                    if(mPagesIV.size() - 1 == currentIndex) {
                        currentIndex = 0;
                    } else {
                        currentIndex++;
                    }
                }
            };
        };
    }

    /**
     * 开始自动滚动
     * @return
     */
    public boolean startAutoScroller(){
        return startTimer();
    }

    /**
     * 停止自动滚动
     */
    public boolean stopAutoScroller(){
        if(mTimer!=null){
            mTimer.cancel();
            mTimer=null;
            return true;
        }else{
            return false;
        }
    }

    private boolean startTimer(){
        if(mTimer==null){
            mTimer = new Timer();
            mTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    Message msg=new Message();
                    msg.what=1;
                    mHandler.sendMessage(msg);
                }
            },3000,3000); //每3秒执行一次
            return true;
        }else{
            return false;
        }
    }

    class CustomPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            if (doNotifyDataSetChangedOnce) {
                doNotifyDataSetChangedOnce = false;
                notifyDataSetChanged();
            }

            return mPagesIV.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            doNotifyDataSetChangedOnce = true;

            container.addView(mPagesIV.get(position));
            return mPagesIV.get(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            doNotifyDataSetChangedOnce = true;

            container.removeView((View) object);
        }

        private boolean doNotifyDataSetChangedOnce = false;
    }

    class CustomOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            for (int i = 0; i < mDotsIV.size(); i++) {
                if (i == position) {
                    mDotsIV.get(i).setImageResource(R.drawable.dot_y);
                } else {
                    mDotsIV.get(i).setImageResource(R.drawable.dot_g);
                }
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            switch (state) {
                //SCROLL_STATE_DRAGGING
                case 1:
                    break;
                //SCROLL_STATE_SETTLING
                case 2:
                    break;
                default:
                    break;
            }
        }
    }
}